<?php


namespace App\Exceptions;


use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use Throwable;

class ExceptionHandler
{
    public static function handle(Throwable $exception, Request $request, Response $response)
    {
        if ($exception instanceof ApiException) {
            if (!$response->isEndResponse()) {
                $data = [
                    "code" => $exception->getCode(),
                    "msg" => $exception->getMessage()
                ];
                $response->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
                $response->withHeader('Content-type', 'application/json;charset=utf-8');
                $response->withStatus(200);
                return true;
            } else {
                return false;
            }
        }
        if ($exception instanceof MissParamsException) {
            if (!$response->isEndResponse()) {
                $data = [
                    "code" => $exception->getCode(),
                    "msg" => $exception->getMessage()
                ];
                $response->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
                $response->withHeader('Content-type', 'application/json;charset=utf-8');
                $response->withStatus(200);
                return true;
            } else {
                return false;
            }
        }

        print_r($exception->getMessage());
    }

}